package org.jeecg.modules.api.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.api.member.entity.Member;
import org.jeecg.modules.api.member.mapper.MemberMapper;
import org.jeecg.modules.api.member.service.IMemberService;
import org.jeecg.modules.api.officebalancelog.service.IOfficeBalanceLogService;
import org.jeecg.modules.api.setting.entity.Setting;
import org.jeecg.modules.api.setting.service.ISettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 用户分销信息
 * @Author: jeecg-boot
 * @Date: 2024-09-19
 * @Version: V1.0
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {
    @Autowired
    private ISettingService settingService;
    @Autowired
    private IOfficeBalanceLogService officeBalanceLogService;

    @Override
    public Member getByOpenid(String openid) {
        return this.getOne(new LambdaQueryWrapper<Member>()
                .eq(Member::getOpenid, openid)
                .last("limit 1")
        );
    }

    @Override
    public void updateLevel(String id) {
        List<Setting> settings = settingService.list(new QueryWrapper<Setting>().eq("is_open", 1).orderByDesc("level"));
        Member member = this.getById(id);
        List<Member> childList = this.list(new QueryWrapper<Member>().eq("recommend_id", member.getId()));
        List<String> ids = childList.stream().map(s -> s.getSourceMemberId()).collect(Collectors.toList());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        String endTime = DateUtils.formatDate(calendar.getTime(), "yyyy-MM-dd");
        calendar.add(Calendar.MONTH, -1);
        String startTime = DateUtils.formatDate(calendar.getTime(), "yyyy-MM-dd");
        int count = officeBalanceLogService.validCount(ids, startTime, endTime);
        log.info("validCount:startTime:{},endTime:{},validCount:{}",startTime,endTime,count);
        int oldlevel = member.getLevel();
        int level = 0;
        for (Setting s : settings) {
            if (count >= s.getNum()) {
                level = s.getLevel();
                break;
            }
        }
        log.info("validCount -level:{}",level);

        if (oldlevel != level) {
            member.setLevel(level);
            this.updateById(member);
        }
    }

    @Override
    public void updateLevelTask() {
        List<Member> list = this.list(new QueryWrapper<Member>().eq("level_state", 1));
        List<Setting> settings = settingService.list(new QueryWrapper<Setting>().eq("is_open", 1).orderByDesc("level"));
        for (Member member : list) {
            List<Member> childList = this.list(new QueryWrapper<Member>().eq("recommend_id", member.getId()));
            List<String> ids = childList.stream().map(s -> s.getSourceMemberId()).collect(Collectors.toList());
            String startTime = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -1);
            String endTime = DateUtils.formatDate(calendar.getTime(), "yyyy-MM-dd");
            int count = officeBalanceLogService.validCount(ids, startTime, endTime);
            log.info("validCount:startTime:{},endTime:{},validCount:{}",count);
            int oldlevel = member.getLevel();
            int level = 0;
            for (Setting s : settings) {
                if (count >= s.getNum()) {
                    level = s.getLevel();
                    break;
                }
            }
            if (oldlevel != level) {
                member.setLevel(level);
                member.setLevelState(0);
                member.setUpdateTime(new Date());
                this.updateById(member);
            }
        }
    }

    @Override
    public List<Member> getRankList(int size) {
        return list(new QueryWrapper<Member>().orderByDesc("commission").last(" limit " + size));
    }

    @Override
    public Member getByPhone(String phone) {
        return this.getOne(new LambdaQueryWrapper<Member>()
                .eq(Member::getPhone, phone)
                .last("limit 1")
        );
    }

    @Override
    public Member getBySourceId(String id) {
        return this.getOne(new LambdaQueryWrapper<Member>()
                .eq(Member::getSourceMemberId, id)
                .last("limit 1")
        );
    }
}
